package com.xbx.admin.controller.upload;

import com.xbx.baseweb.constant.ResponseCode;
import com.xbx.baseweb.controller.ResultUtils;
import com.xbx.baseweb.model.ResponseModel;
import com.xbx.admin.service.upload.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * 下载文件
 *
 * @author 89005691
 * @create 2018-09-22 18:15
 */
@Slf4j
@Controller
@Api(tags = "下载文件")
public class UploadController {

    @Value("${nsfServerPath}")
    private String nsfServerPath;

    @Autowired
    private UploadService uploadService;

    /**
     * 下载项目根目录下excel下的文件
     */
    @ApiOperation(value = "下载模板文件", httpMethod = "GET")
    @GetMapping("/downloadFile")
    @ApiImplicitParam(name = "type", value = "下载模板类型（无参数 test申报导入模板，1 test导入奖项模板，2 年度评优申报导入模板，3 年度评优导入奖项模板，4 速运百杰申请记录导入模板）", example = "1",paramType="query")
    public void downloadFile(HttpServletResponse response, Integer type) {

        String fileName = "申报导入模板.rar";
        String fileRealName = "bestapplyreward.rar";

        if(type != null && type == 1){

            fileName = "导入奖项.zip";
            fileRealName = "bestreward.zip";
        } else if(type != null && type == 2){

            fileName = "年度评优申报导入模板.rar";
            fileRealName = "assessmentapplyreward.rar";
        } else if(type != null && type == 3){

            fileName = "年度评优导入奖项.zip";
            fileRealName = "assessmentreward.zip";
        } else if(type != null && type == 4){

            fileName = "速运百杰申报导入模板.zip";
            fileRealName = "hundredapplyreward.zip";
        }

        String filePath = nsfServerPath + File.separator + "excel" + File.separator + fileRealName;

        log.info("下载文件路径为{}", filePath);

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;

        FileInputStream stream = null;

        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
            response.setContentType("application/octet-stream");

            stream = new FileInputStream(filePath);
            os = response.getOutputStream();
            bis = new BufferedInputStream(stream);
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (FileNotFoundException e1) {

            log.error("系统找不到指定的文件");
        } catch (IOException e) {

            log.error("下载项目根目录下excel下的文件失败");
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {

                    log.error("下载excel模板下的文件关闭流失败，文件路径{}", filePath);
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {

                    log.error("下载excel模板下的文件关闭流失败，文件路径{}", filePath);
                }
            }
        }
    }

    /**
     * 上传文件获取uuid
     */
    @ResponseBody
    @ApiOperation(value = "上传获取uuid，提交表单时带上uuid", httpMethod = "POST")
    @PostMapping("/uploadFile")
    public ResponseModel uploadFile(@RequestParam("file") MultipartFile multipartFile) {

        Map<String, String> result = this.uploadService.uploadFile(multipartFile);

        String msg = result.get("msg");

        if (StringUtils.isNotEmpty(msg)) {

            return ResultUtils.fail(ResponseCode.SERVER_ERROR.getCode(), msg);
        }

        return ResultUtils.success("object", result.get("uuid"));
    }
}
